package com.har.modules.web.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.har.common.exception.RRException;
import com.har.common.utils.*;
import com.har.modules.web.dao.CompanyDao;
import com.har.modules.web.entity.*;
import com.har.modules.web.service.CompanyService;
import com.har.modules.web.service.SmsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@Slf4j
@Service("companyService")
public class CompanyServiceImpl extends ServiceImpl<CompanyDao,CompanyEntity> implements CompanyService {
    @Autowired
    private SmsService smsService;



    @Override
    public CompanyEntity save(CompanyRegisterEntity companyRegisterEntity) throws ParseException {

        CompanyEntity companyEntity= new CompanyEntity();
        EntityWrapper<CompanyEntity> ew=new EntityWrapper<>();

        //验证用户名
        if(StringUtil.strLength(companyRegisterEntity.getUserName())>20){
            throw new RRException("请设置以英文字符开头，4-20位包含英文字符或者数字的用户名。");
        }
        if(StringUtil.strLength(companyRegisterEntity.getUserName())<4){
            throw new RRException("请设置以英文字符开头，4-20位包含英文字符或者数字的用户名。");
        }
        //取首字母验证是否为字母
        String str=companyRegisterEntity.getUserName().substring(0,1);
        log.info("username>>>{}",companyRegisterEntity.getUserName());
        String regex="^[A-Za-z]";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(str);
        // 字符串是否与正则表达式相匹配
        boolean rs = matcher.matches();
        System.out.println(rs);
        if(!matcher.matches()){
            throw new RRException("请设置以英文字符开头，4-20位包含英文字符或者数字的用户名。");
        }
        //验证用户名是否被使用
        if(!StringUtil.isEmpty(companyRegisterEntity.getUserName())){
            ew.eq("user_name",companyRegisterEntity.getUserName());
            CompanyEntity company=this.selectOne(ew);
            //查询
            if(null!=company){
                throw new RRException("账号名已被注册");
            }
        }
        //验证企业全称
        if(StringUtil.isEmpty(companyRegisterEntity.getCompanyName())){
            throw new RRException("企业全称不能为空");
        }
        //验证营业执照号
        if(StringUtil.isEmpty(companyRegisterEntity.getBusinessLicenseNo())){
            throw new RRException("营业执照号(统一社会信用代码)");
        }
        //验证企业地址
        if(StringUtil.isEmpty(companyRegisterEntity.getCompanyAddress())){
            throw new RRException("企业地址不能为空");
        }
        //验证企业联系人
        if(StringUtil.isEmpty(companyRegisterEntity.getLegalPerson())){
            throw new RRException("企业联系人不能为空");
        }
        //验证
        if(!ValidatUtil.checkMobileNumber(companyRegisterEntity.getMobile())) {
            throw new RRException("请输入正确的联系人手机号");
        }
        //通过验证码和手机号进行验证
        Boolean b=smsService.contrastDate(companyRegisterEntity.getMobile(),companyRegisterEntity.getCode());
        if (!b){
            throw new RRException("手机验证码失效，请重新获取验证码");
        }
        companyEntity.setBusinessLicenseNo(companyRegisterEntity.getBusinessLicenseNo());
        companyEntity.setCompanyAddress(companyRegisterEntity.getCompanyAddress());
        companyEntity.setCompanyName(companyRegisterEntity.getCompanyName());
        companyEntity.setLegalPerson(companyRegisterEntity.getLegalPerson());
        companyEntity.setMobile(companyRegisterEntity.getMobile());
        //注册时 为启用
        companyEntity.setStatus(1);
        companyEntity.setUserName(companyRegisterEntity.getUserName());
        //md5加密密码
        companyEntity.setPassword((companyRegisterEntity.getPassword()));
        companyEntity.setCreateTime(new Date());
        this.insert(companyEntity);
        return companyEntity;
    }

    @Override
    public UserLoginEntity selectOne(LoginEntity loginEntity) throws Exception {
        if(StringUtil.isEmpty(loginEntity.getUsername())){
            throw new RRException("请输入用户名");
        }
        if (StringUtil.isEmpty(loginEntity.getPassword())){
            throw new RRException("请输入密码");
        }
        if(StringUtil.isEmpty(loginEntity.getCode())){
            throw  new RRException("请输入验证码");
        }
        if (!StringUtils.equalsIgnoreCase(loginEntity.getCode(), MapUtils.maps.get("nCode"))) {  //忽略验证码大小写
            throw  new RRException("图形验证码错误，请重新获取");
        }

        boolean flag=false;
        CompanyEntity companyEntity=new CompanyEntity();
        if(!flag){
            EntityWrapper<CompanyEntity> ew=new EntityWrapper<>();
            ew.eq("password",loginEntity.getPassword());
            ew.eq("user_name",loginEntity.getUsername());
            companyEntity=this.selectOne(ew);
            if(null==companyEntity){
                flag=true;
            }
        }
        if (flag){
            EntityWrapper<CompanyEntity> ew=new EntityWrapper<>();
            ew.eq("password",loginEntity.getPassword());
            ew.eq("business_license_no",loginEntity.getUsername());
            companyEntity=this.selectOne(ew);
        }
        if(null==companyEntity){
            throw  new RRException("账号或密码错误，请重新输入");
        }
        if(0==companyEntity.getStatus()){
            throw  new RRException("账号未启用，请联系客服");
        }
        log.info("login>>>{}>>>{}>>>{}>>>{}",loginEntity.getType(),loginEntity.getUsername(),
                loginEntity.getPassword(),loginEntity.getCode());

        MapUtils.maps.clear();
        UserLoginEntity userLoginEntity=new UserLoginEntity();
        userLoginEntity.setRealname(companyEntity.getCompanyName());
        userLoginEntity.setUsername(companyEntity.getUserName());
        userLoginEntity.setId(companyEntity.getId());
        userLoginEntity.setType(1);
        JSONObject cookieJson = new JSONObject();
        cookieJson.put("id",companyEntity.getId());
        cookieJson.put("mobile",companyEntity.getMobile());
        cookieJson.put("loginTime",DateUtils.format(new Date(),DateUtils.DATE_TIME_PATTERN));
        cookieJson.put("userName",companyEntity.getUserName());
        //用户类型 1:企业 0:员工
        cookieJson.put("type",1);
        userLoginEntity.setToken(AESUtil.getInstance().encrypt(cookieJson.toJSONString()));
        return userLoginEntity;
    }

    @Override
    public void update(ResetEntity resetEntity) throws ParseException {
        if(StringUtil.isEmpty(resetEntity.getUsername())){
            throw new RRException("登录账号为空");
        }
        if(StringUtil.strLength(resetEntity.getUsername())>20){
            throw new RRException("用户名请输入20位以内字符");
        }
        if(StringUtil.isEmpty(resetEntity.getPassword())){
            throw  new RRException("密码为空");
        }
        if(!ValidatUtil.checkMobileNumber(resetEntity.getMobile())){
            throw  new RRException("请输入正确的手机号");
        }
        CompanyEntity company=new CompanyEntity();
        EntityWrapper<CompanyEntity> ew=new EntityWrapper<>();
        Boolean b=smsService.contrastDate(resetEntity.getMobile(),resetEntity.getCode());
        if (!b){
            throw new RRException("验证码失效，请重新获取验证码");
        }
        if(!StringUtil.isEmpty(resetEntity.getMobile())){
            ew.eq("user_name",resetEntity.getUsername());
            ew.eq("mobile",resetEntity.getMobile());
            company=this.selectOne(ew);
            if(null==company){
                throw  new RRException("企业账号不存在，请先注册或联系客服");
            }
            if (!StringUtil.isEmpty(resetEntity.getPassword())){
                company.setPassword(resetEntity.getPassword());
            }
        }
        company.setUpdateTime(new Date());
        updateById(company);
    }

    @Override
    public CompanyEntity updateOfBack(UserOrCompanyEntity company) throws ParseException {
        EntityWrapper<CompanyEntity> ew=new EntityWrapper<>();
        CompanyEntity companyEntity=new CompanyEntity();
        if(null!=company.getId()){
            companyEntity.setId(company.getId());
        }
        companyEntity=selectOne(ew.eq("id",company.getId()));
        //修改密码
        if(!StringUtil.isEmpty(company.getNewPassword())&&!StringUtil.isEmpty(company.getOldPassword())){

            if(null!=company.getId()&&!StringUtil.isEmpty(company.getOldPassword())){
                ew.eq("id",company.getId())
                        .eq("password",company.getOldPassword());
                CompanyEntity companyEntity1=this.selectOne(ew);
                if(null==companyEntity1){
                    throw  new RRException("原密码错误，请重新输入");
                }
                //设置为新密码
                companyEntity.setPassword(company.getNewPassword());
            }
        }
        //修改企业信息中的企业全称
        if(!StringUtil.isEmpty(company.getCompanyName())){
            companyEntity.setCompanyName(company.getCompanyName());
        }
        //企业营业执照号
        if(!StringUtil.isEmpty(company.getBusinessLicenseNo())){
            companyEntity.setBusinessLicenseNo(company.getBusinessLicenseNo());
        }
        //修改企业联系人
        if(!StringUtil.isEmpty(company.getLegalPerson())&&!StringUtil.isEmpty(company.getNewMobile())){
            //验证当前手机号是否正确
            if(!ValidatUtil.checkMobileNumber(company.getNewMobile())){
                throw  new RRException("请输入正确的手机号");
            }
            //通过原手机验证码和手机号进行验证
            Boolean b=smsService.contrastDate(company.getOldMobile(),company.getOldCode());
            if (!b){
                throw new RRException("原手机验证码失效，请重新获取验证码");
            }

            //通过新手机验证码和手机号进行验证
            Boolean b1=smsService.contrastDate(company.getNewMobile(),company.getNewCode());
            if (!b1){
                throw new RRException("新手机验证码失效，请重新获取验证码");
            }
            companyEntity.setMobile(company.getNewMobile());
            companyEntity.setLegalPerson(company.getLegalPerson());
        }
        //修改企业地址
        if(!StringUtil.isEmpty(company.getCompanyAddress())){
            companyEntity.setCompanyAddress(company.getCompanyAddress());
        }
        //解除微信昵称和openid
        if(!StringUtil.isEmpty(company.getUntieCode())&&!StringUtil.isEmpty(company.getMobile())){
            Boolean b=smsService.contrastDate(company.getMobile(),company.getUntieCode());
            if (!b){
                throw new RRException("手机验证码失效，请重新获取验证码");
            }
            companyEntity.setOpenId(null);
            companyEntity.setNickName(null);
        }
        companyEntity.setUpdateTime(new Date());
        updateAllColumnById(companyEntity);
        return companyEntity;
    }

    @Override
    public UserBackEntity selectById(Long id) {
        if(StringUtil.isEmpty(String.valueOf(id))){
            throw new RRException("id为空，查询失败");
        }
        UserBackEntity com=new UserBackEntity();
        EntityWrapper<CompanyEntity> ew=new EntityWrapper<>();
        //只查询启用的用户
        ew.eq("status",1);
        ew.eq("id",id);
        CompanyEntity companyEntity=this.selectOne(ew);
        if(null!=companyEntity){
            com.setId(companyEntity.getId());
            com.setUserName(companyEntity.getUserName());
            com.setCompanyName(companyEntity.getCompanyName());
            com.setBusinessLicenseNo(companyEntity.getBusinessLicenseNo());
            com.setMobile(companyEntity.getMobile());
            com.setLegalPerson(companyEntity.getLegalPerson());
            com.setCompanyAddress(companyEntity.getCompanyAddress());
            com.setNickName(companyEntity.getNickName());
        }
        return com;
    }

    @Override
    public UCBackEntity queryCompany(Long id, String mobile) {
        UCBackEntity ucBackEntity=new UCBackEntity();
        EntityWrapper<CompanyEntity> ew=new EntityWrapper<>();
        if(!StringUtil.isEmpty(mobile)&&!StringUtil.isEmpty(String.valueOf(id))){
            ew.eq("id",id);
            ew.eq("mobile",mobile);
        }else {
            throw new RRException("id或手机号为空");
        }
        CompanyEntity companyEntity=this.selectOne(ew);
        ucBackEntity.setMobile(companyEntity.getMobile());
        ucBackEntity.setCompanyName(companyEntity.getCompanyName());
        ucBackEntity.setRealname(companyEntity.getLegalPerson());
        return ucBackEntity;
    }

    @Override
    public CompanyBackEntity selectByName(String userName) {
        CompanyBackEntity com=new CompanyBackEntity();
        EntityWrapper<CompanyEntity> ew=new EntityWrapper<>();
        //只查询启用的用户
        ew.eq("status",1);
        ew.eq("user_name",userName);
        CompanyEntity companyEntity=this.selectOne(ew);
        if(null!=companyEntity){
            com.setId(companyEntity.getId());
            com.setUserName(companyEntity.getUserName());
            com.setCompanyName(companyEntity.getCompanyName());
            com.setBusinessLicenseNo(companyEntity.getBusinessLicenseNo());
            com.setMobile(companyEntity.getMobile());
            com.setLegalPerson(companyEntity.getLegalPerson());
            com.setCompanyAddress(companyEntity.getCompanyAddress());
        }else {
            throw new RRException("用户不存在或者该用户未启用");
        }
        return com;
    }

    @Override
    public CompanyEntity queryNickName(Long id) {
        EntityWrapper<CompanyEntity> ew=new EntityWrapper<>();
        ew.eq("id",id);
        CompanyEntity com=this.selectOne(ew);
        com.setPassword(null);
        com.setBusinessLicenseNo(null);
        com.setMobile(null);
        com.setCompanyAddress(null);
        com.setLegalPerson(null);
        com.setOpenId(null);
        com.setStatus(null);
        com.setCreateTime(null);
        com.setUpdateTime(null);
        com.setUserName(null);
        com.setCompanyName(null);
        return com;
    }

    @Override
    public void updateNickName(JSONObject dataJson) {
        //获取微信返回的用户信息
        String userinfo=dataJson.getString("userinfo");
        //用户类型加id
        String state=dataJson.getString("state");
        JSONObject data= (JSONObject) JSONObject.parse(userinfo);
        //微信用户昵称
        String nickName=data.getString("nickname");
        //微信openid
        String openId=data.getString("openid");
        //截取用户id
        Long userId=Long.valueOf(state.substring(1));
        log.info("userId>>>{}",userId);
        CompanyEntity companyEntity=new CompanyEntity();
        companyEntity.setId(userId);
        companyEntity.setOpenId(openId);
        companyEntity.setNickName(nickName);
        companyEntity.setUpdateTime(new Date());
        updateById(companyEntity);
    }
}
